import Vue from 'vue'
import VueRouter from 'vue-router'
import { getToken } from '@/utils/token'
Vue.use(VueRouter)
const routes = [
  {
    path: '/',
    redirect: '/Login'// 重指向
  },
  {
    // 登录
    path: '/Login',
    name: 'Login',
    component: () => import(/* webpackChunkName: "Login" */ '../views/Login/index.vue')
  },
  {
    // 布局(＾－＾)V
    path: '/Layout',
    name: 'Layout',
    component: () => import(/* webpackChunkName: "Login" */ '../views/Layout/index.vue'),
    children: [
      {
        // 首页
        path: '',
        redirect: '/Layout/Home'// 重指向
      },
      {
        // 首页
        path: 'Home',
        name: 'Home',
        meta: {
          scrollTop: 0 // 滚动条位置
        },
        component: () => import(/* webpackChunkName: "Home" */ '../views/Home/index.vue')
      },
      {
        // 用户页
        path: 'User',
        name: 'User',
        component: () => import(/* webpackChunkName: "Home" */ '../views/User/index.vue')
      }
    ]
  },
  {
    // 搜索页
    path: '/Search',
    name: 'Search',
    component: () => import(/* webpackChunkName: "Search" */ '../views/Search/index.vue')
  },
  {
    // 搜索页点击跳转
    /***
     * 动态路由传参  /:kw
     * 1.0 不能用query(因为查询到的是？后面的值)
     * 2.0 跳转的时候用的this.$router.push，也不能用params{}传，因为path会忽略params
     * 3.0 可以用拼接字符串去传
     * this.$router.push({
        path:  `/Searchpach/${val}`
      })
     */
    path: '/Searchpach/:kw',
    name: 'Searchpach',
    component: () => import(/* webpackChunkName: "Search" */ '../views/Search/searchPath.vue')
  },
  {
    // 文章详情页
    path: '/ArticeDetail',
    name: 'ArticeDetail',
    component: () => import('@/views/ArticleDetail/index.vue')
  },
  {
    // 用户信息修改页面
    path: '/userEdit',
    name: 'userEdit',
    component: () => import(/* webpackChunkName: "userEdit" */ '../views/User/userEdit.vue')
  },
  {
    // 小思同学
    path: '/Chat',
    name: 'Chat',
    component: () => import(/* webpackChunkName: "Chat" */'@/views/Chat')
  }
]

const router = new VueRouter({
  routes
})
// 全局的路由守卫（在路由真正的发生改变前，进入次函数）
// 此函数可以决定路由的是否跳转，取消，强制中断到别的路由
router.beforeEach(
  (to, from, next) => {
    // 需求1：假如用户已经登录，则不让他切换登录页面
    if (getToken()?.length > 0 && to.path === '/Login') {
      // 操作： 判断本地有无token，并且去的页面是登录页面，则不放行
      next('/Layout')
    } else {
      next()
    }
  }
)
export default router
